

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文介绍了Vue3相关知识。">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/08/02/Vue3/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文介绍了Vue3相关知识。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/vue3.png">
<meta property="article:published_time" content="2023-08-02T00:00:00.000Z">
<meta property="article:modified_time" content="2024-02-26T12:23:03.359Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="Vue3">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/vue3.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>Vue3 - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Vue3"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-08-02 08:00" pubdate>
          2023年08月02日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          90 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Vue3</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Vue3带来了什么"><a href="#Vue3带来了什么" class="headerlink" title="Vue3带来了什么"></a>Vue3带来了什么</h1><p>github的tags地址：<a target="_blank" rel="noopener" href="https://github.com/vuejs/vue-next/releases/tag/v3.0.0">https://github.com/vuejs/vue-next/releases/tag/v3.0.0</a></p>
<p>1.性能的提升</p>
<ul>
<li>打包大小减少41%</li>
<li>初次渲染快55%,更新渲染快133%</li>
<li>内存减少54%</li>
</ul>
<p>2.源码的升级</p>
<ul>
<li>使用Proxy代替defineProperty实现响应式</li>
<li>重写虚拟DOM的实现和Tree- Shaking</li>
</ul>
<p>3.拥抱TypeScript</p>
<p>Vue3可以更好的支持TypeScript</p>
<p>4.新的特性</p>
<ul>
<li>Composition API（组合API）<ul>
<li>setup配置</li>
<li>ref与reactive</li>
<li>watch与watchEffect</li>
<li>provide与inject</li>
<li>……</li>
</ul>
</li>
<li>新的内置组件<ul>
<li>Fragment</li>
<li>Teleport</li>
<li>Suspense</li>
</ul>
</li>
<li>其他改变<ul>
<li>新的生命周期钩子</li>
<li>data 选项应始终被声明为一个函数</li>
<li>移除keyCode支持作为 v-on 的修饰符</li>
<li>……</li>
</ul>
</li>
</ul>
<h1 id="创建Vue3-0工程"><a href="#创建Vue3-0工程" class="headerlink" title="创建Vue3.0工程"></a>创建Vue3.0工程</h1><p>1.使用 vue-cli 创建</p>
<p>官方文档：<a target="_blank" rel="noopener" href="https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create">https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create</a></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment">## 查看@vue/cli版本，确保@vue/cli版本在4.5.0以上</span><br>vue --version<br><span class="hljs-comment">## 如果不在4.5.0以上版本，安装或者升级你的@vue/cli</span><br>npm install -g @vue/cli<br><span class="hljs-comment">## 创建</span><br>vue create vue3_test<br><span class="hljs-comment">## 启动</span><br><span class="hljs-built_in">cd</span> vue_test<br>npm run serve<br></code></pre></td></tr></table></figure>

<p>2.使用 vite 创建</p>
<p>官方文档：<a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/guide/installation.html#vite">https://v3.cn.vuejs.org/guide/installation.html#vite</a></p>
<p>vite官网：<a target="_blank" rel="noopener" href="https://vitejs.cn/">https://vitejs.cn</a></p>
<ul>
<li>什么是vite？—— 新一代前端构建工具。</li>
<li>优势如下：<ul>
<li>开发环境中，无需打包操作，可快速的<strong>冷启动</strong>。</li>
<li>轻量快速的热重载（HMR）。</li>
<li>真正的按需编译，不再等待整个应用编译完成。</li>
</ul>
</li>
<li>传统构建 与 vite构建对比图</li>
</ul>
<img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/markdown/image-20230802111152075.png" alt="image-20230802111152075" style="zoom: 67%;">

<img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/markdown/image-20230802111207651.png" alt="image-20230802111207651" style="zoom: 67%;">

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment">## 创建工程</span><br>npm init vite-app &lt;project-name&gt;<br><span class="hljs-comment">## 进入工程目录</span><br><span class="hljs-built_in">cd</span> &lt;project-name&gt;<br><span class="hljs-comment">## 安装依赖</span><br>npm install<br><span class="hljs-comment">## 运行 </span><br>npm run dev<br></code></pre></td></tr></table></figure>

<h1 id="常用Composition-API"><a href="#常用Composition-API" class="headerlink" title="常用Composition API"></a>常用Composition API</h1><h2 id="1-拉开序幕的setup"><a href="#1-拉开序幕的setup" class="headerlink" title="1.拉开序幕的setup"></a>1.拉开序幕的setup</h2><ol>
<li>理解：Vue3.0中一个新的配置项，值为一个函数。</li>
<li>setup是所有<strong>Composition API（组合API）</strong>“表演的舞台“。</li>
<li>组件中所用到的：数据、方法等等，均要配置在setup中。</li>
<li>setup函数的两种返回值：<ol>
<li>若返回一个对象，则对象中的属性、方法, 在模板中均可以直接使用。（重点关注！）</li>
<li>若返回一个渲染函数：则可以自定义渲染内容。（了解）</li>
</ol>
</li>
<li>注意点：<ol>
<li>尽量不要与Vue2.x配置混用<ul>
<li>Vue2.x配置（data、methos、computed…）中<strong>可以访问到</strong>setup中的属性、方法。</li>
<li>但在setup中<strong>不能访问到</strong>Vue2.x配置（data、methos、computed…）。</li>
<li>如果有重名, setup优先。</li>
</ul>
</li>
<li>setup不能是一个async函数，因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。（后期也可以返回一个Promise实例，但需要Suspense和异步组件的配合）</li>
</ol>
</li>
</ol>
<h2 id="2-ref函数"><a href="#2-ref函数" class="headerlink" title="2.ref函数"></a>2.ref函数</h2><ul>
<li><p>作用: 定义一个响应式的数据</p>
</li>
<li><p>语法:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> xxx = <span class="hljs-title function_">ref</span>(initValue)<br></code></pre></td></tr></table></figure>

<ul>
<li>创建一个包含响应式数据的<strong>引用对象（reference对象，简称ref对象）</strong>。</li>
<li>JS中操作数据： <code>xxx.value</code></li>
<li>模板中读取数据: 不需要.value，直接：<code>&lt;div&gt;&#123;&#123;xxx&#125;&#125;&lt;/div&gt;</code></li>
</ul>
</li>
<li><p>备注：</p>
<ul>
<li>接收的数据可以是：基本类型、也可以是对象类型。</li>
<li><strong>基本类型的数据</strong>：响应式依然是靠<code>Object.defineProperty()</code>的<code>get</code>与<code>set</code>完成的。</li>
<li><strong>对象类型的数据</strong>：内部 <em>“ 求助 ”</em> 了Vue3.0中的一个新函数—— <code>reactive</code>函数。</li>
</ul>
</li>
</ul>
<h2 id="3-reactive函数"><a href="#3-reactive函数" class="headerlink" title="3.reactive函数"></a>3.reactive函数</h2><ul>
<li>作用: 定义一个<strong>对象类型</strong>的响应式数据（基本类型不要用它，要用<code>ref</code>函数）</li>
<li>语法：<code>const 代理对象= reactive(源对象)</code>接收一个对象（或数组），返回一个<strong>代理对象（Proxy的实例对象，简称proxy对象）</strong></li>
<li>reactive定义的响应式数据是“深层次的”。</li>
<li>内部基于 ES6 的 Proxy 实现，通过代理对象操作源对象内部数据进行操作。</li>
</ul>
<blockquote>
<p>基本都用reactive，基本数据类型不要单独写，封装在对象中交给reactive。</p>
<p><code>let data = reactive(&#123;</code></p>
<p>​      person: {…},</p>
<p>​      student: {…}</p>
<p><code>&#125;)</code></p>
</blockquote>
<h2 id="4-Vue3-0中的响应式原理"><a href="#4-Vue3-0中的响应式原理" class="headerlink" title="4.Vue3.0中的响应式原理"></a>4.Vue3.0中的响应式原理</h2><h3 id="vue2-x的响应式"><a href="#vue2-x的响应式" class="headerlink" title="vue2.x的响应式"></a>vue2.x的响应式</h3><ul>
<li><p>实现原理：</p>
<ul>
<li><p>对象类型：通过<code>Object.defineProperty()</code>对属性的读取、修改进行拦截（数据劫持）。</p>
</li>
<li><p>数组类型：通过重写更新数组的一系列方法来实现拦截。（对数组的变更方法进行了包裹）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(data, <span class="hljs-string">&#x27;count&#x27;</span>, &#123;<br>    get () &#123;&#125;, <br>    set () &#123;&#125;<br>&#125;)<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>存在问题：</p>
<ul>
<li>新增属性、删除属性, 界面不会更新。</li>
<li>直接通过下标修改数组, 界面不会自动更新。</li>
</ul>
</li>
</ul>
<h3 id="Vue3-0的响应式"><a href="#Vue3-0的响应式" class="headerlink" title="Vue3.0的响应式"></a>Vue3.0的响应式</h3><ul>
<li><p>实现原理:</p>
<ul>
<li><p>通过Proxy（代理）: 拦截对象中任意属性的变化, 包括：属性值的读写、属性的添加、属性的删除等。</p>
</li>
<li><p>通过Reflect（反射）: 对源对象的属性进行操作。</p>
</li>
<li><p>MDN文档中描述的Proxy与Reflect：</p>
<ul>
<li><p>Proxy：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy</a></p>
</li>
<li><p>Reflect：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(data, &#123;<br>    <span class="hljs-comment">// 拦截读取属性值</span><br>    get (target, prop) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">get</span>(target, prop)<br>    &#125;,<br>    <span class="hljs-comment">// 拦截设置属性值或添加新属性</span><br>    set (target, prop, value) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">set</span>(target, prop, value)<br>    &#125;,<br>    <span class="hljs-comment">// 拦截删除属性</span><br>    deleteProperty (target, prop) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">deleteProperty</span>(target, prop)<br>    &#125;<br>&#125;)<br><br>proxy.<span class="hljs-property">name</span> = <span class="hljs-string">&#x27;tom&#x27;</span>   <br></code></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="5-reactive对比ref"><a href="#5-reactive对比ref" class="headerlink" title="5.reactive对比ref"></a>5.reactive对比ref</h2><ul>
<li>从定义数据角度对比：<ul>
<li>ref用来定义：<strong>基本类型数据</strong>。</li>
<li>reactive用来定义：<strong>对象（或数组）类型数据</strong>。</li>
<li>备注：ref也可以用来定义<strong>对象（或数组）类型数据</strong>, 它内部会自动通过<code>reactive</code>转为<strong>代理对象</strong>。</li>
</ul>
</li>
<li>从原理角度对比：<ul>
<li>ref通过<code>Object.defineProperty()</code>的<code>get</code>与<code>set</code>来实现响应式（数据劫持）。</li>
<li>reactive通过使用<strong>Proxy</strong>来实现响应式（数据劫持）, 并通过<strong>Reflect</strong>操作<strong>源对象</strong>内部的数据。</li>
</ul>
</li>
<li>从使用角度对比：<ul>
<li>ref定义的数据：操作数据<strong>需要</strong><code>.value</code>，读取数据时模板中直接读取<strong>不需要</strong><code>.value</code>。</li>
<li>reactive定义的数据：操作数据与读取数据：<strong>均不需要</strong><code>.value</code>。</li>
</ul>
</li>
</ul>
<h2 id="6-setup的两个注意点"><a href="#6-setup的两个注意点" class="headerlink" title="6.setup的两个注意点"></a>6.setup的两个注意点</h2><ul>
<li>setup执行的时机<ul>
<li>在beforeCreate之前执行一次，this是undefined。</li>
</ul>
</li>
<li>setup的参数<ul>
<li>props：值为对象，包含：组件外部传递过来，且组件内部声明接收了的属性。</li>
<li>context：上下文对象<ul>
<li>attrs: 值为对象，包含：组件外部传递过来，但没有在props配置中声明的属性, 相当于 <code>this.$attrs</code>。</li>
<li>slots: 收到的插槽内容, 相当于 <code>this.$slots</code>。</li>
<li>emit: 分发自定义事件的函数, 相当于 <code>this.$emit</code>。</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="7-计算属性与监视"><a href="#7-计算属性与监视" class="headerlink" title="7.计算属性与监视"></a>7.计算属性与监视</h2><h3 id="1-computed函数"><a href="#1-computed函数" class="headerlink" title="1.computed函数"></a>1.computed函数</h3><ul>
<li><p>与Vue2.x中computed配置功能一致</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">computed</span>: &#123;<br>    <span class="hljs-title function_">fullName</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">person</span>.<span class="hljs-property">firstName</span> + <span class="hljs-string">&#x27;-&#x27;</span> + <span class="hljs-variable language_">this</span>.<span class="hljs-property">person</span>.<span class="hljs-property">lastName</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>vue3中写法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123;computed&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-title function_">setup</span>(<span class="hljs-params"></span>)&#123;<br>    ...<br>	<span class="hljs-comment">//计算属性——简写</span><br>    <span class="hljs-keyword">let</span> fullName = <span class="hljs-title function_">computed</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>        <span class="hljs-keyword">return</span> person.<span class="hljs-property">firstName</span> + <span class="hljs-string">&#x27;-&#x27;</span> + person.<span class="hljs-property">lastName</span><br>    &#125;)<br>    <span class="hljs-comment">//计算属性——完整</span><br>    <span class="hljs-keyword">let</span> fullName = <span class="hljs-title function_">computed</span>(&#123;<br>        <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>)&#123;<br>            <span class="hljs-keyword">return</span> person.<span class="hljs-property">firstName</span> + <span class="hljs-string">&#x27;-&#x27;</span> + person.<span class="hljs-property">lastName</span><br>        &#125;,<br>        <span class="hljs-title function_">set</span>(<span class="hljs-params">value</span>)&#123;<br>            <span class="hljs-keyword">const</span> nameArr = value.<span class="hljs-title function_">split</span>(<span class="hljs-string">&#x27;-&#x27;</span>)<br>            person.<span class="hljs-property">firstName</span> = nameArr[<span class="hljs-number">0</span>]<br>            person.<span class="hljs-property">lastName</span> = nameArr[<span class="hljs-number">1</span>]<br>        &#125;<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h3 id="2-watch函数"><a href="#2-watch函数" class="headerlink" title="2.watch函数"></a>2.watch函数</h3><ul>
<li><p>与Vue2.x中watch配置功能一致</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">watch</span>: &#123;<br>    <span class="hljs-title function_">sum</span>(<span class="hljs-params">newValue,oldValue</span>) &#123;<br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;sum的值变化了&#x27;</span>,newValue,oldValue);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>两个小“坑”：</p>
<ul>
<li>监视reactive定义的响应式数据时：oldValue无法正确获取、强制开启了深度监视（deep配置失效）。</li>
<li>监视reactive定义的响应式数据中某个属性时：deep配置有效。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//情况一：监视ref定义的响应式数据</span><br><span class="hljs-title function_">watch</span>(sum,<span class="hljs-function">(<span class="hljs-params">newValue,oldValue</span>)=&gt;</span>&#123;<br>	<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;sum变化了&#x27;</span>,newValue,oldValue)<br>&#125;,&#123;<span class="hljs-attr">immediate</span>:<span class="hljs-literal">true</span>&#125;)<br><br><span class="hljs-comment">//情况二：监视多个ref定义的响应式数据</span><br><span class="hljs-title function_">watch</span>([sum,msg],<span class="hljs-function">(<span class="hljs-params">newValue,oldValue</span>)=&gt;</span>&#123;<br>	<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;sum或msg变化了&#x27;</span>,newValue,oldValue)<br>&#125;) <br><br><span class="hljs-comment">/* 情况三：监视reactive定义的响应式数据</span><br><span class="hljs-comment">			若watch监视的是reactive定义的响应式数据，则无法正确获得oldValue！！</span><br><span class="hljs-comment">			若watch监视的是reactive定义的响应式数据，则强制开启了深度监视 </span><br><span class="hljs-comment">*/</span><br><span class="hljs-title function_">watch</span>(person,<span class="hljs-function">(<span class="hljs-params">newValue,oldValue</span>)=&gt;</span>&#123;<br>	<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;person变化了&#x27;</span>,newValue,oldValue)<br>&#125;,&#123;<span class="hljs-attr">immediate</span>:<span class="hljs-literal">true</span>,<span class="hljs-attr">deep</span>:<span class="hljs-literal">false</span>&#125;) <span class="hljs-comment">//此处的deep配置不再奏效</span><br><br><span class="hljs-comment">//情况四：监视reactive定义的响应式数据中的某个属性</span><br><span class="hljs-title function_">watch</span>(<span class="hljs-function">()=&gt;</span>person.<span class="hljs-property">job</span>,<span class="hljs-function">(<span class="hljs-params">newValue,oldValue</span>)=&gt;</span>&#123;<br>	<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;person的job变化了&#x27;</span>,newValue,oldValue)<br>&#125;,&#123;<span class="hljs-attr">immediate</span>:<span class="hljs-literal">true</span>,<span class="hljs-attr">deep</span>:<span class="hljs-literal">true</span>&#125;) <br><br><span class="hljs-comment">//情况五：监视reactive定义的响应式数据中的某些属性</span><br><span class="hljs-title function_">watch</span>([<span class="hljs-function">()=&gt;</span>person.<span class="hljs-property">job</span>,<span class="hljs-function">()=&gt;</span>person.<span class="hljs-property">name</span>],<span class="hljs-function">(<span class="hljs-params">newValue,oldValue</span>)=&gt;</span>&#123;<br>	<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;person的job或者name变化了&#x27;</span>,newValue,oldValue)<br>&#125;,&#123;<span class="hljs-attr">immediate</span>:<span class="hljs-literal">true</span>,<span class="hljs-attr">deep</span>:<span class="hljs-literal">true</span>&#125;)<br><br><span class="hljs-comment">//特殊情况</span><br><span class="hljs-title function_">watch</span>(<span class="hljs-function">()=&gt;</span>person.<span class="hljs-property">job</span>,<span class="hljs-function">(<span class="hljs-params">newValue,oldValue</span>)=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;person的job变化了&#x27;</span>,newValue,oldValue)<br>&#125;,&#123;<span class="hljs-attr">deep</span>:<span class="hljs-literal">true</span>&#125;) <span class="hljs-comment">//此处由于监视的是reactive素定义的对象中的某个属性，所以deep配置有效</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h3 id="3-watchEffect函数"><a href="#3-watchEffect函数" class="headerlink" title="3.watchEffect函数"></a>3.watchEffect函数</h3><ul>
<li><p>watch的套路是：既要指明监视的属性，也要指明监视的回调。</p>
</li>
<li><p>watchEffect的套路是：不用指明监视哪个属性，监视的回调中用到哪个属性，那就监视哪个属性。</p>
</li>
<li><p>watchEffect有点像computed：</p>
<ul>
<li>但computed注重的计算出来的值（回调函数的返回值），所以必须要写返回值。</li>
<li>而watchEffect更注重的是过程（回调函数的函数体），所以不用写返回值。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//watchEffect所指定的回调中用到的数据只要发生变化，则直接重新执行回调。</span><br><span class="hljs-title function_">watchEffect</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>    <span class="hljs-keyword">const</span> x1 = sum.<span class="hljs-property">value</span><br>    <span class="hljs-keyword">const</span> x2 = person.<span class="hljs-property">age</span><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;watchEffect配置的回调执行了&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="8-生命周期"><a href="#8-生命周期" class="headerlink" title="8.生命周期"></a>8.生命周期</h2><p><strong>vue3.0的生命周期</strong></p>
<img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/ markdown/vue3生命周期.png" alt="vue3生命周期" style="zoom: 50%;">

<ul>
<li>Vue3.0中可以继续用配置项方式使用Vue2.x中的生命周期钩子，但有有两个被更名：<ul>
<li><code>beforeDestroy</code>改名为 <code>beforeUnmount</code></li>
<li><code>destroyed</code>改名为 <code>unmounted</code></li>
</ul>
</li>
<li>Vue3.0也提供了 Composition API 形式的生命周期钩子，与Vue2.x中钩子对应关系如下：<ul>
<li><code>beforeCreate</code>&#x3D;&#x3D;&gt;<code>setup()</code></li>
<li><code>created</code>&#x3D;&#x3D;&gt;<code>setup()</code></li>
<li><code>beforeMount</code> &#x3D;&#x3D;&gt;<code>onBeforeMount</code></li>
<li><code>mounted</code>&#x3D;&#x3D;&gt;<code>onMounted</code></li>
<li><code>beforeUpdate</code>&#x3D;&#x3D;&gt;<code>onBeforeUpdate</code></li>
<li><code>updated</code> &#x3D;&#x3D;&gt;<code>onUpdated</code></li>
<li><code>beforeUnmount</code> &#x3D;&#x3D;&gt;<code>onBeforeUnmount</code></li>
<li><code>unmounted</code> &#x3D;&#x3D;&gt;<code>onUnmounted</code></li>
</ul>
</li>
</ul>
<h2 id="9-自定义hook函数"><a href="#9-自定义hook函数" class="headerlink" title="9.自定义hook函数"></a>9.自定义hook函数</h2><ul>
<li>什么是hook？—— 本质是一个函数，把setup函数中使用的Composition API进行了封装。</li>
<li>类似于vue2.x中的mixin。</li>
<li>自定义hook的优势: 复用代码, 让setup中的逻辑更清楚易懂。</li>
</ul>
<h2 id="10-toRef"><a href="#10-toRef" class="headerlink" title="10.toRef"></a>10.toRef</h2><ul>
<li>作用：创建一个 ref 对象，其value值指向另一个对象中的某个属性。</li>
<li>语法：<code>const name = toRef(person,&#39;name&#39;)</code></li>
<li>应用: 要将响应式对象中的某个属性单独提供给外部使用时。</li>
<li>扩展：<code>toRefs</code> 与<code>toRef</code>功能一致，但可以批量创建多个 ref 对象，语法：<code>toRefs(person)</code></li>
</ul>
<h1 id="其他Composition-API"><a href="#其他Composition-API" class="headerlink" title="其他Composition API"></a>其他Composition API</h1><h2 id="1-shallowReactive-与-shallowRef"><a href="#1-shallowReactive-与-shallowRef" class="headerlink" title="1.shallowReactive 与 shallowRef"></a>1.shallowReactive 与 shallowRef</h2><ul>
<li>shallowReactive：只处理对象最外层属性的响应式（浅响应式）。</li>
<li>shallowRef：只处理基本数据类型的响应式, 不进行对象的响应式处理。</li>
<li>什么时候使用?<ul>
<li>如果有一个对象数据，结构比较深, 但变化时只是外层属性变化 &#x3D;&#x3D;&#x3D;&gt; shallowReactive。</li>
<li>如果有一个对象数据，后续功能不会修改该对象中的属性，而是生新的对象来替换 &#x3D;&#x3D;&#x3D;&gt; shallowRef。</li>
</ul>
</li>
</ul>
<h2 id="2-readonly-与-shallowReadonly"><a href="#2-readonly-与-shallowReadonly" class="headerlink" title="2.readonly 与 shallowReadonly"></a>2.readonly 与 shallowReadonly</h2><ul>
<li>readonly: 让一个响应式数据变为只读的（深只读）。</li>
<li>shallowReadonly：让一个响应式数据变为只读的（浅只读）。</li>
<li>应用场景: 不希望数据(尤其是这个数据是来自与其他组件时)被修改时。</li>
</ul>
<h2 id="3-toRaw-与-markRaw"><a href="#3-toRaw-与-markRaw" class="headerlink" title="3.toRaw 与 markRaw"></a>3.toRaw 与 markRaw</h2><ul>
<li>toRaw：<ul>
<li>作用：将一个由<code>reactive</code>生成的<strong>响应式对象</strong>转为<strong>普通对象</strong>。</li>
<li>使用场景：用于读取响应式对象对应的普通对象，对这个普通对象的所有操作，不会引起页面更新。</li>
</ul>
</li>
<li>markRaw：<ul>
<li>作用：标记一个对象，使其永远不会再成为响应式对象。</li>
<li>应用场景:<ol>
<li>有些值不应被设置为响应式的，例如复杂的第三方类库等。</li>
<li>当渲染具有不可变数据源的大列表时，跳过响应式转换可以提高性能。</li>
</ol>
</li>
</ul>
</li>
</ul>
<h2 id="4-customRef"><a href="#4-customRef" class="headerlink" title="4.customRef"></a>4.customRef</h2><ul>
<li><p>作用：创建一个自定义的 ref，并对其依赖项跟踪和更新触发进行显式控制。</p>
</li>
<li><p>实现防抖效果：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;template&gt;<br>	<span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">&quot;keyword&quot;</span>&gt;</span></span><br><span class="language-xml">	<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>&#123;&#123;keyword&#125;&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span></span><br><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span><br><br><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="language-javascript"><span class="language-xml">	<span class="hljs-keyword">import</span> &#123;ref,customRef&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span></span></span><br><span class="language-javascript"><span class="language-xml">	<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;</span></span><br><span class="language-javascript"><span class="language-xml">		<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;Demo&#x27;</span>,</span></span><br><span class="language-javascript"><span class="language-xml">		<span class="hljs-title function_">setup</span>(<span class="hljs-params"></span>)&#123;</span></span><br><span class="language-javascript"><span class="language-xml">			<span class="hljs-comment">// let keyword = ref(&#x27;hello&#x27;) //使用Vue准备好的内置ref</span></span></span><br><span class="language-javascript"><span class="language-xml">			<span class="hljs-comment">//自定义一个myRef</span></span></span><br><span class="language-javascript"><span class="language-xml">			<span class="hljs-keyword">function</span> <span class="hljs-title function_">myRef</span>(<span class="hljs-params">value,delay</span>)&#123;</span></span><br><span class="language-javascript"><span class="language-xml">				<span class="hljs-keyword">let</span> timer</span></span><br><span class="language-javascript"><span class="language-xml">				<span class="hljs-comment">//通过customRef去实现自定义</span></span></span><br><span class="language-javascript"><span class="language-xml">				<span class="hljs-keyword">return</span> <span class="hljs-title function_">customRef</span>(<span class="hljs-function">(<span class="hljs-params">track,trigger</span>)=&gt;</span>&#123;</span></span><br><span class="language-javascript"><span class="language-xml">					<span class="hljs-keyword">return</span>&#123;</span></span><br><span class="language-javascript"><span class="language-xml">						<span class="hljs-title function_">get</span>(<span class="hljs-params"></span>)&#123;</span></span><br><span class="language-javascript"><span class="language-xml">							<span class="hljs-title function_">track</span>() <span class="hljs-comment">//告诉Vue这个value值是需要被“追踪”的</span></span></span><br><span class="language-javascript"><span class="language-xml">							<span class="hljs-keyword">return</span> value</span></span><br><span class="language-javascript"><span class="language-xml">						&#125;,</span></span><br><span class="language-javascript"><span class="language-xml">						<span class="hljs-title function_">set</span>(<span class="hljs-params">newValue</span>)&#123;</span></span><br><span class="language-javascript"><span class="language-xml">							<span class="hljs-built_in">clearTimeout</span>(timer)</span></span><br><span class="language-javascript"><span class="language-xml">							timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;</span></span><br><span class="language-javascript"><span class="language-xml">								value = newValue</span></span><br><span class="language-javascript"><span class="language-xml">								<span class="hljs-title function_">trigger</span>() <span class="hljs-comment">//告诉Vue去更新界面</span></span></span><br><span class="language-javascript"><span class="language-xml">							&#125;,delay)</span></span><br><span class="language-javascript"><span class="language-xml">						&#125;</span></span><br><span class="language-javascript"><span class="language-xml">					&#125;</span></span><br><span class="language-javascript"><span class="language-xml">				&#125;)</span></span><br><span class="language-javascript"><span class="language-xml">			&#125;</span></span><br><span class="language-javascript"><span class="language-xml">			<span class="hljs-keyword">let</span> keyword = <span class="hljs-title function_">myRef</span>(<span class="hljs-string">&#x27;hello&#x27;</span>,<span class="hljs-number">500</span>) <span class="hljs-comment">//使用程序员自定义的ref</span></span></span><br><span class="language-javascript"><span class="language-xml">			<span class="hljs-keyword">return</span> &#123;</span></span><br><span class="language-javascript"><span class="language-xml">				keyword</span></span><br><span class="language-javascript"><span class="language-xml">			&#125;</span></span><br><span class="language-javascript"><span class="language-xml">		&#125;</span></span><br><span class="language-javascript"><span class="language-xml">	&#125;</span></span><br><span class="language-javascript"><span class="language-xml"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="5-provide-与-inject"><a href="#5-provide-与-inject" class="headerlink" title="5.provide 与 inject"></a>5.provide 与 inject</h2><ul>
<li><p>作用：实现<strong>祖与后代组件间</strong>通信</p>
</li>
<li><p>套路：父组件有一个 <code>provide</code> 选项来提供数据，后代组件有一个 <code>inject</code> 选项来开始使用这些数据</p>
</li>
<li><p>具体写法：</p>
<ol>
<li><p>祖组件中：</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs lasso">setup()&#123;<br>    <span class="hljs-params">...</span><span class="hljs-params">...</span><br>    <span class="hljs-keyword">let</span> car = reactive(&#123;name:<span class="hljs-string">&#x27;奔驰&#x27;</span>,price:<span class="hljs-string">&#x27;40万&#x27;</span>&#125;)<br>    <span class="hljs-keyword">provide</span>(<span class="hljs-string">&#x27;car&#x27;</span>,car)<br>    <span class="hljs-params">...</span><span class="hljs-params">...</span><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>后代组件中：</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs lasso">setup(props,context)&#123;<br>    <span class="hljs-params">...</span><span class="hljs-params">...</span><br>    const car = inject(<span class="hljs-string">&#x27;car&#x27;</span>)<br>    <span class="hljs-keyword">return</span> &#123;car&#125;<br>    <span class="hljs-params">...</span><span class="hljs-params">...</span><br>&#125;<br></code></pre></td></tr></table></figure></li>
</ol>
</li>
</ul>
<blockquote>
<p>后代组件都可以用用inject，但是父子之间一般直接用props即可。</p>
</blockquote>
<h2 id="6-响应式数据的判断"><a href="#6-响应式数据的判断" class="headerlink" title="6.响应式数据的判断"></a>6.响应式数据的判断</h2><ul>
<li>isRef: 检查一个值是否为一个 ref 对象</li>
<li>isReactive: 检查一个对象是否是由 <code>reactive</code> 创建的响应式代理</li>
<li>isReadonly: 检查一个对象是否是由 <code>readonly</code> 创建的只读代理</li>
<li>isProxy: 检查一个对象是否是由 <code>reactive</code> 或者 <code>readonly</code> 方法创建的代理</li>
</ul>
<h1 id="Composition-API-的优势"><a href="#Composition-API-的优势" class="headerlink" title="Composition API 的优势"></a>Composition API 的优势</h1><h2 id="1-Options-API-存在的问题"><a href="#1-Options-API-存在的问题" class="headerlink" title="1.Options API 存在的问题"></a>1.Options API 存在的问题</h2><p>使用传统OptionsAPI中，新增或者修改一个需求，就需要分别在data，methods，computed里修改 。</p>
<h2 id="2-Composition-API-的优势"><a href="#2-Composition-API-的优势" class="headerlink" title="2.Composition API 的优势"></a>2.Composition API 的优势</h2><p>我们可以更加优雅的组织我们的代码，函数。让相关功能的代码更加有序的组织在一起。</p>
<h1 id="新的组件"><a href="#新的组件" class="headerlink" title="新的组件"></a>新的组件</h1><h2 id="1-Fragment"><a href="#1-Fragment" class="headerlink" title="1.Fragment"></a>1.Fragment</h2><ul>
<li>在Vue2中: 组件必须有一个根标签</li>
<li>在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中</li>
<li>好处: 减少标签层级, 减小内存占用</li>
</ul>
<h2 id="2-Teleport"><a href="#2-Teleport" class="headerlink" title="2.Teleport"></a>2.Teleport</h2><ul>
<li><p>什么是Teleport？—— <code>Teleport</code> 是一种能够将我们的<strong>组件html结构</strong>移动到指定位置的技术。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">teleport</span> <span class="hljs-attr">to</span>=<span class="hljs-string">&quot;移动位置&quot;</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">&quot;isShow&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;mask&quot;</span>&gt;</span><br>		<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;dialog&quot;</span>&gt;</span><br>			<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>我是一个弹窗<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span><br>			<span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">&quot;isShow = false&quot;</span>&gt;</span>关闭弹窗<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br>		<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br>	<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">teleport</span>&gt;</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="3-Suspense"><a href="#3-Suspense" class="headerlink" title="3.Suspense"></a>3.Suspense</h2><ul>
<li><p>等待异步组件时渲染一些额外内容，让应用有更好的用户体验</p>
</li>
<li><p>使用步骤：</p>
<ul>
<li><p>异步引入组件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 动态引入组件</span><br><span class="hljs-keyword">import</span> &#123;defineAsyncComponent&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><span class="hljs-keyword">const</span> <span class="hljs-title class_">Child</span> = <span class="hljs-title function_">defineAsyncComponent</span>(<span class="hljs-function">()=&gt;</span><span class="hljs-keyword">import</span>(<span class="hljs-string">&#x27;./components/Child.vue&#x27;</span>))<br></code></pre></td></tr></table></figure>
</li>
<li><p>使用<code>Suspense</code>包裹组件，并配置好<code>default</code> 与 <code>fallback</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;app&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>我是App组件<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-slot:default</span>&gt;</span><br>                // 要显示的组件<br>                <span class="hljs-tag">&lt;<span class="hljs-name">Child</span>/&gt;</span><br>            <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span><br>            // 组件还没加载出来的时候显示<br>            <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-slot:fallback</span>&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>加载中.....<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span><br>            <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span><br></code></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<h1 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h1><h2 id="1-全局API的转移"><a href="#1-全局API的转移" class="headerlink" title="1.全局API的转移"></a>1.全局API的转移</h2><ul>
<li><p>Vue 2.x 有许多全局 API 和配置。</p>
<ul>
<li><p>例如：注册全局组件、注册全局指令等。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//注册全局组件</span><br><span class="hljs-title class_">Vue</span>.<span class="hljs-title function_">component</span>(<span class="hljs-string">&#x27;MyButton&#x27;</span>, &#123;<br>  <span class="hljs-attr">data</span>: <span class="hljs-function">() =&gt;</span> (&#123;<br>    <span class="hljs-attr">count</span>: <span class="hljs-number">0</span><br>  &#125;),<br>  <span class="hljs-attr">template</span>: <span class="hljs-string">&#x27;&lt;button @click=&quot;count++&quot;&gt;Clicked &#123;&#123; count &#125;&#125; times.&lt;/button&gt;&#x27;</span><br>&#125;)<br><br><span class="hljs-comment">//注册全局指令</span><br><span class="hljs-title class_">Vue</span>.<span class="hljs-title function_">directive</span>(<span class="hljs-string">&#x27;focus&#x27;</span>, &#123;<br>  <span class="hljs-attr">inserted</span>: <span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> el.<span class="hljs-title function_">focus</span>()<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>Vue3.0中对这些API做出了调整：</p>
<ul>
<li><p>将全局的API，即：<code>Vue.xxx</code>调整到应用实例（<code>app</code>）上</p>
<table>
<thead>
<tr>
<th>2.x 全局 API（<code>Vue</code>）</th>
<th>3.x 实例 API (<code>app</code>)</th>
</tr>
</thead>
<tbody><tr>
<td>Vue.config.xxxx</td>
<td>app.config.xxxx</td>
</tr>
<tr>
<td>Vue.config.productionTip</td>
<td><strong>移除</strong></td>
</tr>
<tr>
<td>Vue.component</td>
<td>app.component</td>
</tr>
<tr>
<td>Vue.directive</td>
<td>app.directive</td>
</tr>
<tr>
<td>Vue.mixin</td>
<td>app.mixin</td>
</tr>
<tr>
<td>Vue.use</td>
<td>app.use</td>
</tr>
<tr>
<td>Vue.prototype</td>
<td>app.config.globalProperties</td>
</tr>
</tbody></table>
</li>
</ul>
</li>
</ul>
<h2 id="2-其他改变"><a href="#2-其他改变" class="headerlink" title="2.其他改变"></a>2.其他改变</h2><ul>
<li><p>data选项应始终被声明为一个函数。（防止组件在被复用的时候参数数据的关联关系造成干扰）</p>
</li>
<li><p>过度类名的更改：</p>
<ul>
<li><p>Vue2.x写法</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs stylus"><span class="hljs-selector-class">.v-enter</span>,<br><span class="hljs-selector-class">.v-leave-to</span> &#123;<br>  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0</span>;<br>&#125;<br><span class="hljs-selector-class">.v-leave</span>,<br><span class="hljs-selector-class">.v-enter-to</span> &#123;<br>  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">1</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>Vue3.x写法</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs css"><span class="hljs-selector-class">.v-enter-from</span>,<br><span class="hljs-selector-class">.v-leave-to</span> &#123;<br>  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0</span>;<br>&#125;<br><br><span class="hljs-selector-class">.v-leave-from</span>,<br><span class="hljs-selector-class">.v-enter-to</span> &#123;<br>  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">1</span>;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p><strong>移除</strong>keyCode作为 v-on 的修饰符，同时也不再支持<code>config.keyCodes</code></p>
</li>
<li><p><strong>移除</strong><code>v-on.native</code>修饰符</p>
<ul>
<li><p>父组件中绑定事件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;my-component<br>  v-<span class="hljs-attr">on</span>:close=<span class="hljs-string">&quot;handleComponentEvent&quot;</span><br>  v-<span class="hljs-attr">on</span>:click=<span class="hljs-string">&quot;handleNativeClickEvent&quot;</span><br>/&gt;<br></code></pre></td></tr></table></figure>
</li>
<li><p>子组件中声明自定义事件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-javascript"></span><br><span class="language-javascript">  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;</span><br><span class="language-javascript">    <span class="hljs-attr">emits</span>: [<span class="hljs-string">&#x27;close&#x27;</span>]</span><br><span class="language-javascript">  &#125;</span><br><span class="language-javascript"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p><strong>移除</strong>过滤器（filter）</p>
<blockquote>
<p>过滤器虽然这看起来很方便，但它需要一个自定义语法，打破大括号内表达式是 “只是 JavaScript” 的假设，这不仅有学习成本，而且有实现成本！建议用方法调用或计算属性去替换过滤器。</p>
</blockquote>
</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/%E6%A1%86%E6%9E%B6/" class="category-chain-item">框架</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/Vue3/">#Vue3</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Vue3</div>
      <div>https://airfe.gitee.io/blog/2023/08/02/Vue3/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年8月2日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/10/20/%E8%B7%A8%E5%9F%9F%E6%96%B9%E6%B3%95/" title="跨域方法">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">跨域方法</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/07/08/%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF/" title="事件循环">
                        <span class="hidden-mobile">事件循环</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
